<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 驾驶员详情 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }"
                  :rules="editModel != 0 ? rules : {}">
      <a-spin :spinning="loading">
        <!-- 驾驶员信息 -->
        <a-card :bordered="false">
          <title-name title="驾驶员信息" />
          <custom-form :form-list="formList" :form="form" :edit-model="editModel == 0 ? 'V' : ''"
                       @onSelectChange="onSelectChange">
            <template v-slot:driverTypeId>
              <a-radio-group v-model="form.driverTypeId" :disabled="editModel == 0 ? true : false"
                             @change="changeDriverTypeVal">
                <a-radio :value="item.code" v-for="(item, index) in driverTypeData" :key="index">
                  {{ item.name }}
                </a-radio>
              </a-radio-group>
            </template>
          </custom-form>
        </a-card>
        <!-- 满意度调查记录和日常考核记录 -->
        <a-card v-if="editModel == 0" :bordered="false">
          <a-tabs v-model="activeKey" @change="search">
            <a-tab-pane key="1" tab="满意度调查记录" />
            <a-tab-pane key="2" tab="日常考核记录" />
          </a-tabs>
          <!-- 统计 -->
          <div class="mb20">
            <span>平均分：{{ (activeKey == 1 ? form.satisfactionAvgScore : form.assessAvgScore) || 0 }}</span>
            <a-divider type="vertical" />
            <span>{{
                activeKey == 1 ? `评价人数：${form.satisfactionPersonSum || 0}` : `考核次数：${form.assessSum || 0}`
            }}</span>
          </div>
          <!-- 表格 -->
          <s-table ref="table" table-layout="fixed" size="default" row-key="id" :columns="columns"
                   :data="loadData" show-size-changer show-quick-jumper show-pagination="auto">
            <template slot="action" slot-scope="text, record">
              <a @click="handleManage(record.id)">查看</a>
            </template>
          </s-table>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <a-button v-if="editModel != 0" :loading="loading" type="primary" class="button_right"
                  @click="handleSubmit">
          提交
        </a-button>
        <a-button type="primary" @click="handleActiveClose">
          关闭
        </a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import { STable } from '@/components' // 表格
import { carDriverInfo, carUsePersonScore, carDriverAssess } from '@/api/office/vehicle/config' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import { createValidator, isPhone, idCard } from '@/utils/regExpression' // 正则校验
import SelectOrgPeople from '@/components/Select/SelectOrgPeople' // 人员
import Selector from '@/components/Select/Selector' // 枚举
import { getDataDict } from '@/api/office/supervise.js'
export default {
  extends: new BaseEditPage(),
  components: {
    STable
  },
  data() {
    return {
      driverTypeData: [],//司机类别数据源
      loading: false, // 提交按钮loding
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      activeKey: '1', // tabs控件，1：满意度调查记录；2 日常考核记录
      form: {
        idCard: void 0,
        birthDay: void 0,
        sex: void 0,
        phone: void 0,
        postStarId: void 0,
        salary: void 0,
        driverName: void 0
      }, // 表单
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, { query: { driverId: this.driverId } })
        let api = this.activeKey == 1 ? carUsePersonScore : carDriverAssess
        return api.getList(requestParameters).then((res) => {
          return res
        })
      },
      defaultPhone: '', // 默认号码
      init: false, // 初始化标识
      rules: {
        driverTypeId: [{ required: true, message: '请选择驾驶员性质', trigger: 'change' }],
        driverId: [{ required: true, whitespace: true, message: '请选择驾驶员姓名', trigger: 'change' }],
        driverName: [{ required: true, whitespace: true, message: '请输入驾驶员姓名', trigger: 'change' }],
        idCard: [{ required: true, validator: createValidator(idCard, '请输入正确的身份证', true), trigger: 'change' }],
        phone: [{ required: true, validator: createValidator(isPhone, '请输入正确的手机号码', true), trigger: 'change' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        birthDay: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
        inJobTime: [{ required: true, message: '请选择入职时间', trigger: 'change' }],
        state: [{ required: true, message: '请选择状态', trigger: 'change' }],
        address: [{ required: true, whitespace: true, message: '请输入现住址', trigger: 'change' }]
      } // 校验规则
    }
  },
  computed: {
    // 表头
    columns() {
      return [
        {
          title: '序号',
          width: 80,
          dataIndex: 'index',
          customRender() {
            return arguments[2] + 1
          }
        },
        {
          title: `${this.activeKey === '2' ? '考核' : '评价'}日期`,
          ellipsis: true,
          dataIndex: 'createTime'
        },
        {
          title: '得分(100分)',
          ellipsis: true,
          dataIndex: 'score'
        },
        {
          title: `${this.activeKey === '2' ? '考核' : '评价'}人`,
          ellipsis: true,
          dataIndex: this.activeKey === '2' ? 'createUserName' : 'creator'
        },
        {
          title: `${this.activeKey === '2' ? '考核' : '评价'}明细`,
          dataIndex: 'action',
          width: 120,
          align: 'center',
          fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ]
    },
    // 表单列表
    formList() {
      return [
        {
          keyName: 'unitName',
          type: 'BaseInput',
          disabled: true,
          label: '所属单位'
        },
        {
          keyName: 'driverTypeId',
          type: 'a-radio-group',
          label: '司机类别',
          slot: true,
        },
        {
          keyName: 'driverId',
          viewName: 'driverName',
          hidden: this.form.driverTypeId === 'ZN',
          type: SelectOrgPeople,
          placeholder: '请选择驾驶员',
          label: '驾驶员姓名',
          attrs: {
            requestParams: {
              orgCodes: [this.$currentPost().code + 'A'],
              rootOrgId: this.$currentPost().id,
              and: true
            },
            init: true
          }
        },
        {
          keyName: 'driverName',
          hidden: this.form.driverTypeId === 'GZ',
          type: 'BaseInput',
          label: '驾驶员姓名'
        },
        {
          keyName: 'idCard',
          type: 'BaseInput',
          label: '身份证号'
        },
        {
          keyName: 'sex',
          type: 'a-select',
          label: '性别',
          placeholder: '请选择性别',
          customRender(e) {
            return ['女', '男'][e]
          },
          data: [
            {
              label: '女',
              value: 0
            },
            {
              label: '男',
              value: 1
            }
          ]
        },
        {
          keyName: 'birthDay',
          type: 'a-date-picker',
          placeholder: '请选择出生日期',
          label: '出生日期',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'phone',
          type: 'BaseInput',
          label: '手机号'
        },
        {
          keyName: 'address',
          type: 'BaseInput',
          label: '现住址',
          attrs: {
            maxLength: 30
          }
        },
        {
          keyName: 'inJobTime',
          type: 'a-date-picker',
          placeholder: '请选择入职时间',
          label: '入职时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'postStarId',
          viewName: 'postStarName',
          label: '现岗位星级',
          hidden: this.form.driverTypeId === 'ZN',
          type: Selector,
          attrs: {
            selectType: '14',
            valueName: 'code',
            urlType: 'union'
          }
        },
        {
          keyName: 'salary',
          hidden: this.form.driverTypeId === 'ZN',
          type: 'BaseInputNumber',
          label: '现岗位薪资(元)',
          precision: 2,
          attrs: {
            min: 0,
            max: 999999999
          }
        },
        {
          keyName: 'state',
          viewName: 'stateName',
          label: '状态',
          type: Selector,
          attrs: {
            valueName: 'code',
            selectType: '15',
            urlType: 'union'
          }
        }
      ]
    }
  },
  watch: {
    // 监听驾驶员性质，重置岗位星级和薪资标准
    'form.driverTypeId'() {
      if (this.init && this.editModel != 0) {
        this.form.postStarId = void 0
        this.form.salary = void 0
      }
    }
  },
  mounted() {
    this.$route.meta.title = ['驾驶员查看', '驾驶员编辑', '驾驶员新增'][this.editModel]
    this.getDataDicts();
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading = true
      carDriverInfo
        .detail({ id: this.id })
        .then((res) => {
          this.loading = false
          this.form = res.data
          this.defaultPhone = res.data.phone
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    } else {
      const post = this.$currentPost()
      // 默认状态为可用
      this.$set(this.form, 'state', '1')
      // 默认驾驶员性质为购置
      this.$set(this.form, 'driverTypeId', 'GZ')
      // 初始化单位
      this.$set(this.form, 'unitName', (post.code === 'PD' ? post.orgName + '-' : '') + post.name)
      this.$set(this.form, 'unitId', post.id)
    }
  },
  methods: {
    async getDataDicts() {
      let res = await getDataDict({ type: '13' })
      if (res.data && res.data.length) {
        this.driverTypeData = res.data;
      }
    },
    //司机类别变更
    changeDriverTypeVal() {
      let _this = this;
      _this.$nextTick(() => {
        //重置已填写的驾驶员信息
        let fieldArr = ['driverId', 'driverName', 'idCard', 'sex', 'birthDay', 'phone', 'address', 'inJobTime'];
        for (let i in fieldArr) {
          if (fieldArr[i] === 'sex') {
            _this.form[fieldArr[i]] = 0;
          } else {
            _this.form[fieldArr[i]] = "";
          }
        }
        //移除表单项的校验结果
        _this.$refs.ruleForm.clearValidate(fieldArr);
      })
    },
    /**
     * 操作栏
     */
    handleManage(id) {
      let query = {
        id,
        checkType: this.activeKey
      }
      this.$router.push({
        name: '/vehicle/driverManagementDetail',
        query
      })
    },
    /**
     * 搜索
     */
    search() {
      this.$refs.table.refresh(true)
    },
    /**
     * 选择人员回调
     */
    onSelectChange() {
      if (arguments[0] === 'driverId') {
        // 映射身份证
        this.form.idCard = arguments[1].idCard
        // 映射姓名
        this.form.driverName = arguments[1].name
        // 出生年月
        this.form.birthDay = arguments[1].birthday
        // 映射性别
        this.form.sex = arguments[1].sex ? Number(arguments[1].sex) : void 0
        // 映射手机
        this.form.phone = arguments[1].phone
      }
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      let that = this
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          that.$confirm({
            title: '温馨提示',
            content: '请确认是否要提交',
            onOk: () => {
              let name = ['update', 'create'][that.editModel - 1] // 根据操作切换url地址
              // 提交表单
              let form = that.$clone(that.form)
              // 提交表单
              return carDriverInfo[name](form).then((res) => {
                // 当驾驶员性质为租赁:1.新增时；2：编辑，且修改过账号
                // if (
                //   form.driverTypeId === 'ZN' &&
                //   (that.editModel == 2 || (that.editModel == 1 && that.defaultPhone != form.phone))
                // ) {
                //   that.$success({
                //     title: '提交成功',
                //     content: (
                //       <div>
                //         <div>已为该租赁司机创建账号，可登录APP，用于接收本人的出行信息以及其他操作。</div>
                //         <div>账号名称：{form.phone}</div>
                //       </div>
                //     ),
                //     okText: '确定',
                //     onOk: () => {
                //       that.$message.success('提交成功！')
                //       that.$multiTab.close()
                //     }
                //   })
                // } else {
                if (res.code === '0') {
                  that.$message.success('提交成功！')
                  that.$multiTab.close()
                } else {
                  that.$message.warning(res.msg)
                }
                // }
              })
            }
          })
        }
      })
    }
  }
}
</script>